<?php
namespace app\backmanage\controller;

use app\common\model\common\Anchor as Model;
use thans\layuiAdmin\facade\Json;
use thans\layuiAdmin\facade\Utils;
use thans\layuiAdmin\Traits\FormActions;
use think\Request;

use thans\layuiAdmin\model\Admins;

use think\facade\View;

class Anchor extends Base
{
    use FormActions;

    protected $route_alias = 'anchor';
    protected $title       = '主播管理';

     public function list(Request $request)
    {
        if ($request->isAjax()||$request->isPost()) {
            list($where, $order, $page, $limit) = Utils::buildParams('partition_id|mobile');
            $mobile='';
            $partitionId='';
            $isTest='';
            foreach ($where as $key => $value) {
                if ($value[0] == 'mobile') {
                    unset($where[$key]);
                    $mobile=$value[2];
                }
                if ($value[0] == 'partition_id') {
                    unset($where[$key]);
                    $partitionId=$value[2];
                }
                if ($value[0] == 'is_test') {
                    unset($where[$key]);
                    $isTest=$value[2];
                }
            }
            //查询符合条件分区信息
            $model  = new Model();
            if(is_numeric($partitionId)){
                $filterWhere[]=['partition_id','=',$partitionId];
            }
            if(is_numeric($isTest)){
                $filterWhere[]=['is_test','=',$isTest];
            }
            if($mobile){
                $filterWhere[]=['mobile','=',$mobile];
            }
            $filterWhere[]=['status','in',[1,3]];
            $partitions=$model->where($filterWhere)->page($page, $limit)->order('id','desc')->field('*')->select()->toArray();
            $partitionCount=$model->where($filterWhere)->count();
            //对用户数据进行分区整理
            $mobileDistributions=[];
            foreach($partitions as $partition){
                $mobileDistributions[$partition['partition_id']][]=$partition['mobile'];
            }
            $configs = $this->getAllPartitionConfigs();
            //进行多项目查询
            $mobileInfos=[];
            foreach($mobileDistributions as $partition_id=>$partition_mobiles){
                $config=$configs[$partition_id]??[];
                if(empty($config)){
                    continue;
                }
                $dnmodel=$this->getPartitionDatabase($partition_id);
                if (!$dnmodel) {
                    continue;
                }
                $memberDatas=$dnmodel->table('member')->where('mobile','in',$partition_mobiles)->where('status','in',[1,3])->column([
                        'id as anchor_id',
                        'mobile as anchor_mobile',
                        'nickname as anchor_nickname',
                        'uuid as anchor_uuid',
                        'create_time',
                        'balance',
                        'vip_end_time',
                        'vip_id',
                        'is_vip',
                        'auth_state',
                        'status'
                    ],'mobile');
                foreach($memberDatas as $mobile=>$memberData){
                    $mobileInfos[$mobile] =$memberData;
                }
            }
            //查询主播是否涉及迁移表
            $anchorMigrations=(new \app\common\model\common\AnchorMigration())->order('id','asc')->column('status','anchor_platform_id');
            foreach($partitions as &$partition){
                $mobileInfo=$mobileInfos[$partition['mobile']]??[];
                $config=$configs[$partition_id]??[];
                $partition=array_merge($partition,$mobileInfo,$config);
                $partition['pc_url']=sprintf("%s?auCode=%s", trim($partition['pc_url'],'/'),think_encrypt((string)$mobileInfo['anchor_id']));
                $partition['create_time']=date('Y-m-d H:i:s',$partition['create_time']);
                $partition['vip_end_time']=$partition['vip_end_time']?date('Y-m-d H:i:s',$partition['vip_end_time']):"-/-";
                $partition['is_migration']=$anchorMigrations[$partition['id']]??-1;
                $partition['anchor_platform_id']=$partition['id'];
            }
            Json::success('获取成功', $partitions, ['total' => $partitionCount,'count' => $partitionCount]);
        }else{
            $data['cols'] = [
                ['field' => 'id', 'title' => 'ID', 'width' => 70],
                ['field' => 'partition_id', 'title' => '分区号', 'width' => 80],
                ['field' => 'partition_name', 'title' => '分区名称', 'width' => 100],
                ['field' => 'anchor_id', 'title' => '主播ID', 'width' => 90],
                ['field' => 'anchor_uuid', 'title' => '主播UUID', 'sort' => true, 'width' => 120],
                ['field' => 'anchor_mobile', 'title' => '主播手机号', 'width' => 120],
                ['field' => 'anchor_nickname', 'title' => '主播昵称', 'width' => 120],
                ['field' => 'is_test', 'title' => '账号类型', 'width' => 100,'type' => "button",'option' => [[0, '正式主播', 'normal'],[1, '测试主播','warm']]],
                ['field' => 'status', 'title' => '用户状态', 'width' => 100,'type' => "button",'option' => [[1, '正常', 'normal'],[3, '封禁','danger']]],
                ['field' => 'auth_state', 'title' => '实名状态', 'width' => 100,'type' => "button",'option' => [[1, '已认证', 'normal'],[0, '未认证','']]],
                ['field' => 'is_vip', 'title' => '会员卡状态', 'width' => 100, 'type' => "button",'option' => [[0, '未开通',''],[1, '正常', 'normal'],[2, '过期','danger']]],
                ['field' => 'vip_id', 'title' => '是否开卡', 'type' => "button", 'option' => [[0, '未开卡'], [1, '月卡',''],[6, '月卡',''], [2, '年卡', 'normal'],[8, '年卡', 'normal'],[7, '季卡',''], [3, '体验版'], [5, '专属年卡', 'danger']],'width'=>100],
                ['field' => 'vip_end_time', 'title' => '会员卡到期时间', 'width' => 180],
                ['field' => 'balance', 'title' => '流量余额(元)', 'width' => 120],
                ['field' => 'pc_url', 'title' => 'PC登录地址', 'width' => 150],
                ['field' => 'create_time', 'title' => '注册时间', 'width' => 180],
                ['field' => 'right', 'title' => '操作', 'toolbar' => '#barDemo', 'width' => 450, 'fixed' => 'right'],
            ];
            $data['title'] = $this->title;
            list($partitionId,$partitions)=\app\common\model\common\PartitionPackage::getPartitionPackageInfo();
            $data['search'][] = ['type' => 'select', 'field' => 'partition_id', 'desc' => '分区号', 'option' => $partitions,'default'=>$partitionId];
            $data['search'][] = ['type' => 'select', 'field' => 'is_test', 'desc' => '账号类型', 'option' => [0=>'正式主播',1=>'测试主播']];
            $data['search'][] = ['type' => 'text', 'field' => 'mobile', 'desc' => '请输入主播手机号搜索'];
            //url init
            $data['list_url']           = '/backmanage/' . $this->route_alias . '/list';
            $data['create_url']           = '/backmanage/' . $this->route_alias . '/create';
            $data['huanBang_url']= '/backmanage/anchorChangeMobile/create';
            $data['fenJin_url']= '/backmanage/' . $this->route_alias . '/fenJin';
            $data['qianYi_url']= '/backmanage/' . $this->route_alias . '/qianYi';
            $data['qianYiLog_url']= '/backmanage/' . $this->route_alias . '/anchorMigrations';
            $data['zhuXiao_url']= '/backmanage/' . $this->route_alias . '/zhuXiao';
            $data['partition_id']=$partitionId;
            return View::fetch('anchor/index', $data);
        }
    }

    public function create(Request $request)
    {
         if ($request->isPost()) {
            $mobile=$request->param('mobile','');
            $partitionId=$request->param('partition_id',null);
            if(!$mobile){
                return json(['code'=>-1,'msg'=>'手机号码不能为空']);
            }
            //检测新增手机号是否已存在
            $model  = new Model();
            $anchor=$model->where([
                'mobile'=>$mobile,
                'status'=>1
            ])->find();
            if(!empty($anchor->id)){
                return json(['code'=>-1,'msg'=>'该手机号已存在，请更换后重试']);
            }
            if(!isset($partitionId)){
                return json(['code'=>-1,'msg'=>'分区ID不能为空']);
            }
            $subMemberModel=$this->getPartitionDatabase($partitionId);
            if (!$subMemberModel) {
                return json(['code'=>-1,'msg'=>'分区号无效']);
            }
            //检测该手机号在字库是否存在
            $num=$subMemberModel->table('member')->where([
                'mobile' => $mobile,
                'status' =>1
            ])->count();
            if(!$num){
                $homeNickName=config('nickName.HomeName');
                $backNickName=config('nickName.BackName');
                $headPortrait=config('headPortrait');
                $insert=[
                    'account'=> $mobile,
                    'uuid'   =>getUUID($partitionId,1),
                    'nickname'=>$homeNickName[array_rand($homeNickName)] . $backNickName[array_rand($backNickName)],
                    'head_img'=>$headPortrait[array_rand($headPortrait)],
                    'mobile'=> $mobile,
                    'vip_id'=>0,
                    'is_vip'=>0,
                    'vip_end_time'=>0,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];
                $ret=$subMemberModel->table('member')->insert($insert);
                if(!$ret){
                    return json(['code'=>-1,'msg'=>'该手机号创建主播失败，请重试']);
                }
            }
            //主播表新增
            $model->insert([
                "mobile" =>  $mobile,
                "partition_id"=>$partitionId,
                "create_time"=>time(),
                "is_test"=>1
            ]);
            return json(['code'=>0,'msg'=>'该手机号创建成功']);
         }else{
            $partitionOptions=[];
            $allocatePartitionIds=\app\common\model\common\PartitionPackage::where('status',1)->order('partition_id','asc')->column('partition_id');
            foreach ($allocatePartitionIds as $allocatePartitionId) {
                $partitionOptions[]=[$allocatePartitionId,sprintf("分区-%s",$allocatePartitionId)];
            }
            $data['cols'] = [
                ['field' => 'mobile', 'title' => '新增手机号','desc'=>'请输入手机号'],
                ['field' => 'partition_id', 'title' => '分区号','type' => "button", 'option' => $partitionOptions],
            ];
            $data['title'] = $this->title;
            $data['create_url'] = '/backmanage/' . $this->route_alias . '/create';
            return View::fetch('anchor/add', $data);
         }
    }

    //封禁
    public function fenJin(Request $request){
        $id=$request->param('id',0);
        $status=$request->param('status',0);
        if(!$id){
             return json(['code'=>-1,'msg'=>'ID无效']);
        }
        if(!$status){
             return json(['code'=>-1,'msg'=>'设置状态无效']);
        }
        //查询主播信息
        $model  = new Model();
        $anchor=$model->where('id',$id)->find();
        if(empty($anchor->id)){
            return json(['code'=>-1,'msg'=>'ID无效']);
        }
        $subMemberModel=$this->getPartitionDatabase($anchor['partition_id']);
        if (!$subMemberModel) {
            return json(['code'=>-1,'msg'=>'分区号无效']);
        }
        if($status==1){
            $filterStatus=3;
        }else{
            $filterStatus=1;
        }
        $member=$subMemberModel->table('member')->where([
            'mobile' => $anchor['mobile'],
            'status' =>$filterStatus
        ])->field(['id','nickname'])->find();
        if(empty($member['id'])){
            return json(['code'=>-1,'msg'=>'主播数据异常，请排查']);
        }
        //更新主播状态
        $ret=$subMemberModel->table('member')->where('id',$member['id'])->update([
            'status'=>$status,
            'update_time'=>time()
        ]);
        if(!$ret){
            return json(['code'=>-1,'msg'=>'主播数据更新异常，请排查']);
        }
        $content=($status==1)?'当前主播【'.$member['nickname'].'】已经被平台解封':'当前主播【'.$member['nickname'].'】已经被平台封禁';
        $insert = [
            'member_id'=>$member['id'],
            'content'  => $content,
            'create_time'=>time(),
            'update_time'=>time()
        ];
        $subMemberModel->table('platform_log')->insert($insert);
        return json(['code'=>0,'msg'=>$content]);
    }

    //注销
    public function zhuXiao(Request $request){
        $id=$request->param('id',0);
        if(!$id){
             return json(['code'=>-1,'msg'=>'ID无效']);
        }
        //查询主播信息
        $model  = new Model();
        $anchor=$model->where('id',$id)->find();
        if(empty($anchor->id)){
            return json(['code'=>-1,'msg'=>'ID无效']);
        }
        $subMemberModel=$this->getPartitionDatabase($anchor['partition_id']);
        if (!$subMemberModel) {
            return json(['code'=>-1,'msg'=>'分区号无效']);
        }
        $member=$subMemberModel->table('member')->where([
            'mobile' => $anchor['mobile'],
        ])->where('status','in',[1,3])->field(['id','nickname'])->find();
        if(empty($member['id'])){
            return json(['code'=>-1,'msg'=>'主播数据异常，请排查']);
        }
        //更新主播状态
        $ret=$subMemberModel->table('member')->where('id',$member['id'])->update([
            'status'=>2,
            'update_time'=>time()
        ]);
        if(!$ret){
            return json(['code'=>-1,'msg'=>'主播数据更新异常，请排查']);
        }
        //注销通用库主播数据
        $model->where('id',$id)->update([
            'status'=>2,
            'update_time'=>time()
        ]);
        $content='当前主播【'.$member['nickname'].'】已经被平台注销';
        $insert = [
            'member_id'=>$member['id'],
            'content'  => $content,
            'create_time'=>time(),
            'update_time'=>time()
        ];
        $subMemberModel->table('platform_log')->insert($insert);
        return json(['code'=>0,'msg'=>'该主播注销成功']);
    }

    //主播迁移
    public function qianYi(Request $request){
        $id=$request->param('id','');
        if(!$id){
             return json(['code'=>-1,'msg'=>'ID不能为空']);
        }
        //查询主播信息
        $model  = new Model();
        $anchor=$model->where('id',$id)->find();
        if(empty($anchor->id)){
            return json(['code'=>-1,'msg'=>'ID无效']);
        }
        $subMemberModel=$this->getPartitionDatabase($anchor['partition_id']);
        if (!$subMemberModel) {
            return json(['code'=>-1,'msg'=>'分区号无效']);
        }
        $member=$subMemberModel->table('member')->where([
                'mobile' => $anchor['mobile'],
                'status' =>1
            ])->find();
        if(empty($member['id'])){
            return json(['code'=>-1,'msg'=>'未匹配到该手机号在子库中的记录']);
        }
        if ($request->isPost()) {
            //接收待迁入分区ID
            $partition_id=$request->param('partition_id','');
            if($partition_id===''){
                return json(['code'=>-1,'msg'=>'分区号不能为空']);
            }
            if($partition_id==$anchor['partition_id']){
                 return json(['code'=>-1,'msg'=>'分区号不能一致']);
            }
            //避免子库中存在相同手机号
            $subCurMemberModel=$this->getPartitionDatabase($partition_id);
            if (!$subCurMemberModel) {
                return json(['code'=>-1,'msg'=>'分区号无效']);
            }
            $submember=$subCurMemberModel->table('member')->where([
                'mobile' => $anchor['mobile'],
                'status' =>1
            ])->find();
            if(!empty($submember['id'])){
                return json(['code'=>-1,'msg'=>'检测到该手机号已出现在待迁入的子库中，请解决冲突后重试']);
            }

            //拼装入库数据
            $insert=[
                'anchor_platform_id'=>$anchor->id,
                'migration_id'=>date('YmdHis',time()).rand(1000,9999),
                'migration_mobile'=>$anchor['mobile'],
                'migration_out_partition_id'=>$anchor['partition_id'],
                'migration_out_anchor_id'=>$member['id'],
                'migration_in_partition_id'=>$partition_id,
                'migration_in_anchor_id'=>0,
                'admin_id'=>session('admins_id'),
                'create_time'=>time()
            ];
           $ret=(new \app\common\model\common\AnchorMigration())->insert($insert);
           if(!$ret){
                 return json(['code'=>-1,'msg'=>'主播数据迁移任务创建失败']);
           }
           return json(['code'=>0,'msg'=>'主播数据迁移任务创建成功']);
        }else{
            //获取已用分区情况
            list($partitionDefaultId,$partitions)=\app\common\model\common\PartitionPackage::getPartitionPackageInfo();
            $data['anchor_nickname']=$member['nickname'];
            $data['anchor_mobile']=$member['mobile'];
            $data['partition_id']=$anchor['partition_id'];
            $data['partition_name']=$partitions[$anchor['partition_id']]??'';
            $data['id']=$id;
            //计算分区主播分布情况
            $partitionData=[];
            $partitionPackageList=\app\common\model\common\PartitionPackage::getPartitionPackageList();
            $partitionPackageListData=array_column($partitionPackageList,null,'partition_id');
            foreach($partitionPackageListData as $partitionId=>$config){
                $subMemberModel=$this->getPartitionDatabase($partitionId);
                if (!$subMemberModel) {
                    continue;
                }
                $num=$subMemberModel->table('member')->where('status','=',1)->where('vip_id','>',0)->count();
                $partitionData[$partitionId]['allocation_num']=$num;
                $vipNum=$subMemberModel->table('member')->where('status','=',1)->where('auth_state','1')->where('vip_id','>',0)->where('vip_end_time','>',time())->count();
                $partitionData[$partitionId]['vip_num']=$vipNum;
                $partitionData[$partitionId]['partition_name']=$config['partition_name'];
                 $partitionData[$partitionId]['partition_id']=$partitionId;
            }
            $data['allocation_num']=$partitionData[$data['partition_id']]['allocation_num']??0;
            $data['vip_num']=$partitionData[$data['partition_id']]['vip_num']??0;
            $data['partition_list']=array_values($partitionData);
            return View::fetch('anchor/qian_yi', $data);
        }
    }

    //主播迁移记录
    public function anchorMigrations(Request $request){
        $anchor_platform_id=$request->param('anchor_platform_id','');
        if ($request->isAjax()) {
            list($where, $order, $page, $limit) = Utils::buildParams('anchor_platform_id');
             foreach ($where as $key => $value) {
                if ($value[0] == 'anchor_platform_id') {
                    unset($where[$key]);
                    $anchor_platform_id=$value[2];
                }
            }
            //查询主播信息
            $model  =(new \app\common\model\common\AnchorMigration());
            if($anchor_platform_id){
               $model=$model->where('anchor_platform_id',$anchor_platform_id);
            }
            list($partitionDefaultId,$partitions)=\app\common\model\common\PartitionPackage::getPartitionPackageInfo();
            $lists=$model->select()->toArray();
            $adminIds=array_column($lists,'admin_id');
            $admin=(new Admins())->whereIn('id',$adminIds)->column('nickname','id');
            foreach($lists as &$list){
                $list['migration_out_partition_name']=$partitions[$list['migration_out_partition_id']]??'';
                $list['migration_in_partition_name']=$partitions[$list['migration_in_partition_id']]??'';
                $list['admin_name']=$admin[$list['admin_id']]??'';
                if(!$list['update_time']){
                    $list['update_time']="-/-";
                }
            }
            $count=$model->count();
            Json::success('获取成功', $lists, ['total' => $count,'count' => $count]);
        }else{
            $data = [];
            $data['cols'] = [
                ['field' => 'id', 'title' => 'ID', 'sort' => true, 'width' => '8%'],
                ['field' => 'anchor_platform_id', 'title' => '主播平台ID', 'width' => '10%'],
                ['field' => 'migration_id', 'title' => '迁移任务ID', 'width' => '10%'],
                ['field' => 'status', 'title' => '任务状态', 'width' => 100,'type' => "button",'option' => [[0, '未处理', ''],[1, '处理中', 'normal'],[2, '已完成','warm'],[3, '迁移失败','warm']]],
                ['field' => 'migration_mobile', 'title' => '迁移关联手机号', 'width' => '15%'],
                ['field' => 'migration_out_partition_id', 'title' => '迁出分区ID', 'width' => '10%'],
                ['field' => 'migration_out_partition_name', 'title' => '迁出分区名称', 'width' => '10%'],
                ['field' => 'migration_out_anchor_id', 'title' => '迁出主播ID', 'width' => '10%'],
                ['field' => 'migration_in_partition_id', 'title' => '迁入分区ID', 'width' => '10%'],
                ['field' => 'migration_in_partition_name', 'title' => '迁入分区名称', 'width' => '10%'],
                ['field' => 'migration_in_anchor_id', 'title' => '迁入主播ID', 'width' => '10%'],
                ['field' => 'admin_name', 'title' => '操作人', 'width' => '10%'],
                ['field' => 'create_time', 'title' => '操作时间', 'width' => '15%'],
                ['field' => 'update_time', 'title' => '处理时间', 'width' => '15%'],
            ];
            $data['title'] ="主播迁移日志管理" ;
            //url init
            $data['list_url'] = '/backmanage/' . $this->route_alias . '/anchorMigrations';
            $data['anchor_platform_id']=$anchor_platform_id;
            return View::fetch('anchor/qian_yi_list', $data);
        }
    }

}